import 'dart:io';

import 'package:color_dart/RgbaColor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'dart:convert';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:im_flutter_sdk_example/provider/app_model.dart';
import 'package:im_flutter_sdk_example/provider/comment_model.dart';
import 'package:im_flutter_sdk_example/provider/group_message.dart';
import 'package:im_flutter_sdk_example/provider/news_model.dart';
import 'package:im_flutter_sdk_example/provider/user_model.dart';
import 'package:im_flutter_sdk_example/utils/update.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'components/custom_animation.dart';
import 'provider/counter_model.dart';
import 'provider/group_formdate_model.dart';

import 'provider/interest_model.dart';

import 'provider/comment_model.dart';
import 'provider/message_model.dart';
import 'provider/moment_model.dart';
import 'provider/tag_model.dart';
import 'utils/global.dart';
import 'utils/localizations.dart';
import 'package:im_flutter_sdk_example/routes/index.dart' as GKRouter;
import 'package:flutter_screenutil/screenutil_init.dart';

final GKRouter.Router router = GKRouter.Router();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String user = prefs.getString('user');
  if (user != null && user.isNotEmpty) {
    G.user.init(json.decode(user));
  }
  SystemChrome.setEnabledSystemUIOverlays([]);
  //
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: CounterModel()),
        ChangeNotifierProvider.value(value: GroupFormDataModel()),
        ChangeNotifierProvider.value(value: (CommentModelProvider())),
        ChangeNotifierProvider.value(value: (NewsModelProvider())),
        ChangeNotifierProvider(create: (context) {
          return MomentProvider();
        }),
        ChangeNotifierProvider.value(value: EasyMobProvider()),
        ChangeNotifierProvider.value(value: GroupMessageProvider()),
        ChangeNotifierProvider.value(value: InterestProvider()),
        ChangeNotifierProvider.value(value: TagProvider()),
        ChangeNotifierProvider.value(value: UserProvider()),
        ChangeNotifierProvider(create: (context) {
          return AppProvider();
        }),
      ],
      child: MyApp(),
    ),
  );
  configLoading();
}

void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.doubleBounce
    ..loadingStyle = EasyLoadingStyle.custom
    ..indicatorSize = 35.0
    ..radius = 5.0
    ..progressColor = rgba(34, 34, 34, 1)
    ..backgroundColor = rgba(42, 125, 250, 1)
    ..indicatorColor = Colors.white
    ..textColor = Colors.white
    ..maskColor = Colors.black.withOpacity(0.5)
    ..userInteractions = true
    ..dismissOnTap = true
    ..customAnimation = CustomAnimation();
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> implements EMConnectionListener {
  @override
  void initState() {
    super.initState();
    initEaseMobSDK();
    doAppUpdate();
  }

  Future doAppUpdate() async {
    await Future.delayed(Duration(seconds: 3), () async {
      if (await Permission.storage.isGranted == false) {
        await [Permission.storage].request();
      }
      if (await Permission.storage.isGranted) {
        AppUpdateUtil().run(context);
      }
    });
  }

  void initEaseMobSDK() async {
    EMOptions options = EMOptions(appKey: 'huipaysns#zhiku-news');
    EMPushConfig config = EMPushConfig();
    // 判断是否为debug模式
    if (!kReleaseMode) {
      config
        ..enableAPNs("2882303761519021652")
        // ..enableOppPush('oppoAppKey', 'oppoAppSecret')
        ..enableHWPush()
        ..enableFCM('fcmId')
        ..enableMeiZuPush('mzAppId', 'mzAppKey')
        ..enableMiPush('2882303761519021652', '5691902177652');
    } else {
      config
        ..enableAPNs('2882303761519021652')
        // ..enableOppPush('oppoAppKey', 'oppoAppSecret')
        ..enableHWPush()
        ..enableFCM('fcmId')
        ..enableMeiZuPush('mzAppId', 'mzAppKey')
        ..enableMiPush('2882303761519021652', '5691902177652');
    }

    options.debugModel = true;
    options.pushConfig = config;

    await EMClient.getInstance.init(options);
    EMClient.getInstance.addConnectionListener(this);
    //    EMClient.getInstance.callManager.registerCallSharedManager();
    //    EMClient.getInstance.conferenceManager.registerConferenceSharedManager();
    // setState(() {
    //   isLogin = EMClient.getInstance.isLoginBefore;
    // });
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(750, 1334),
      allowFontScaling: false,
      builder: () => MaterialApp(
          debugShowCheckedModeBanner: false,
          title: '联合科创',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MaterialApp(
              navigatorKey: G.navigatorKey,
              debugShowCheckedModeBanner: false,
              localizationsDelegates: [
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                DemoLocalizationsDelegate.delegate,
              ],
              supportedLocales: [
                // const Locale('en', 'US'), // 美国英语
                const Locale('zh', 'CH'), // 中文简体
                // ... other locales the app supports
              ],
              title: '科创汇',
              // initialRoute: '/quick_login',
              initialRoute: '/index',
              // initialRoute: '/login_password',
              // initialRoute: '/login_method',
              // initialRoute: '/login_registe',
              onGenerateRoute: router.getRoutes,
              builder: EasyLoading.init())),
    );
  }

  @override
  void onConnected() {
    print('环信 已连接');
  }

  @override
  void onDisconnected(int errorCode) {}
}
